import router from "@/router/router.ts";
import Nprogress from "nprogress";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/cookie.ts";
import useUserStore from "@/pinia/modules/user/userStore.ts";
import useMenuStore from "@/pinia/menu.ts";
import { asyncRoutes } from "@/router/routes/asyncRoutes.ts";
import { cloneDeep } from "lodash";

const whiteList: string[] = ["/login", "/404"];

router.beforeEach(async (to, from, next) => {
  Nprogress.start();
  const token: string = getToken();
  const userStore = useUserStore();
  if (token) {
    if (to.path === "/login") {
      next(false);
      ElMessage.warning("已经登录");
    } else {
      if (userStore.userInfo.name !== "") {
        next();
      } else {
        try {
          const { routes } = await userStore.fetchUserInfo();
          const menuStore = useMenuStore();
          // 过滤路由生成最终路由
          const resultRoutes: any[] = menuStore.filterAsyncRoutes(cloneDeep(asyncRoutes), routes);
          resultRoutes.forEach(item => {
            router.addRoute(item);
          });
          next();
        } catch (error: any) {
          userStore.logout();
          next({ path: "/login", query: { redirect_url: to.fullPath } });
          console.log(from);
        }
      }
    }
  } else {
    if (whiteList.includes(to.path)) {
      next();
    } else {
      next({ path: "/login", query: { redirect: to.fullPath } });
      ElMessage.warning("请您登录");
    }
  }
});

router.afterEach(() => {
  Nprogress.done();
});
